package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserReportVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 苏成博
 * @date 2023-02-11 15:41
 */
@Service
public class UserServiceImpl implements UserService {
    //微信服务接口地址
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public User userLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口服务，获得当前微信用户的openid
        String code = userLoginDTO.getCode();
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //判断openid是否为空，如果为空表示登录失败，抛出业务异常
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //判断当前用户是否为新用户
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            //则是新用户，新增用户
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now()).build();
            userMapper.saveUser(user);
        }
        return user;
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //统计日期
        List<LocalDate> dateList=new ArrayList<>();
        while (!begin.isEqual(end)){
            dateList.add(begin);
            begin=begin.plusDays(1);
        }
        dateList.add(end);
        //统计用户总量，select count(id) form user where create_time < begin
        //统计新增用户 select count(id) from user where create_time between createTimeMin and createTimeMax
        ArrayList<Integer> countTotalUserList = new ArrayList<>();
        ArrayList<Integer> countNewUserList =new ArrayList<>();
        Integer countTotalUser;
        Integer countNewUser;
        for (LocalDate localDate : dateList) {
            //封装用户总数
            countTotalUser=userMapper.findTotalUser(localDate.atTime(LocalTime.MAX));
            countTotalUser=countTotalUser==null?0:countTotalUser;
            countTotalUserList.add(countTotalUser);
            //统计新增用户
            countNewUser=userMapper.findNewUser(localDate.atTime(LocalTime.MIN),localDate.atTime(LocalTime.MAX));
            countNewUser=countNewUser==null?0:countNewUser;
            countNewUserList.add(countNewUser);
        }
        return new UserReportVO(
                StringUtils.join(dateList,","),
                StringUtils.join(countTotalUserList,","),
                StringUtils.join(countNewUserList,",")
        );
    }
}
